import { defineStore } from 'pinia'
import type { Event, EventType, CreateEventForm, DietType, CalendarEvent, RecurrencePattern } from '@/types'
import { formatDate } from '@/utils/date'
import { mockEventTypes, mockDietTypes, mockEvents, mockDelay } from '@/api/mock'
import { LocalStorageManager } from '@/utils/localStorage'

// 生成重复事件的辅助函数
const generateRecurringEvents = (baseEvent: Event, pattern: RecurrencePattern): Event[] => {
  const recurringEvents: Event[] = []
  const startDate = new Date(baseEvent.start_date)
  let currentDate = new Date(startDate)

  // 计算结束条件
  const maxCount = pattern.count || 50 // 默认最多50次
  const endDate = pattern.end_date ? new Date(pattern.end_date) : null

  for (let i = 1; i < maxCount; i++) {
    // 根据频率计算下一个日期
    switch (pattern.frequency) {
      case 'daily':
        currentDate.setDate(currentDate.getDate() + pattern.interval)
        break
      case 'weekly':
        currentDate.setDate(currentDate.getDate() + (pattern.interval * 7))
        break
      case 'monthly':
        currentDate.setMonth(currentDate.getMonth() + pattern.interval)
        break
    }

    // 检查是否超过结束日期
    if (endDate && currentDate > endDate) {
      break
    }

    // 创建重复事件
    const recurringEvent: Event = {
      ...baseEvent,
      id: baseEvent.id + i, // 简单的ID生成策略
      start_date: formatDate(currentDate, 'YYYY-MM-DD'),
      end_date: baseEvent.end_date ? formatDate(new Date(currentDate.getTime() + (new Date(baseEvent.end_date).getTime() - startDate.getTime())), 'YYYY-MM-DD') : undefined,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    }

    recurringEvents.push(recurringEvent)
  }

  return recurringEvents
}

export const useEventsStore = defineStore('events', () => {
  // 状态
  const events = ref<Event[]>([])
  const eventTypes = ref<EventType[]>([])
  const dietTypes = ref<DietType[]>([])
  const loading = ref(false)
  
  // 获取事件列表
  const fetchEvents = async (_params?: { start_date?: string; end_date?: string }) => {
    loading.value = true
    try {
      await mockDelay(500)

      // 首先尝试从本地存储加载
      const localEvents = LocalStorageManager.getEvents()
      if (localEvents.length > 0) {
        events.value = localEvents
        console.log('从本地存储加载了', localEvents.length, '个事件')
      } else {
        // 如果本地存储为空，使用mock数据并保存到本地存储
        events.value = mockEvents
        LocalStorageManager.saveEvents(mockEvents)
        console.log('使用mock数据并保存到本地存储')
      }

      return true
    } catch (error) {
      console.error('Fetch events error:', error)
      return false
    } finally {
      loading.value = false
    }
  }
  
  // 获取事件类型
  const fetchEventTypes = async () => {
    try {
      await mockDelay(300)
      eventTypes.value = mockEventTypes
      return true
    } catch (error) {
      console.error('Fetch event types error:', error)
      return false
    }
  }
  
  // 获取饮食类型
  const fetchDietTypes = async () => {
    try {
      await mockDelay(300)
      dietTypes.value = mockDietTypes
      return true
    } catch (error) {
      console.error('Fetch diet types error:', error)
      return false
    }
  }
  
  // 创建事件
  const createEvent = async (form: CreateEventForm) => {
    try {
      // 模拟API延迟
      await mockDelay(500)

      // 生成主事件
      const newEvent: Event = {
        id: Date.now(),
        user_id: 1,
        event_type_id: form.event_type_id,
        title: form.title,
        description: form.description,
        start_date: form.start_date,
        end_date: form.end_date,
        start_time: form.start_time,
        end_time: form.end_time,
        duration_type: form.duration_type,
        duration_value: form.duration_value,
        recurrence_pattern: form.recurrence_pattern,
        is_completed: false,
        completed_at: undefined,
        priority: form.priority,
        extra_data: form.extra_data,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }

      events.value.push(newEvent)

      // 如果有重复模式，生成重复事件
      if (form.recurrence_pattern) {
        const repeatEvents = generateRecurringEvents(newEvent, form.recurrence_pattern)
        events.value.push(...repeatEvents)
      }

      // 保存到本地存储
      LocalStorageManager.saveEvents(events.value)
      console.log('事件已保存到本地存储')

      return newEvent
    } catch (error) {
      console.error('Create event error:', error)
      return null
    }
  }
  
  // 更新事件
  const updateEvent = async (id: number, data: Partial<Event>) => {
    try {
      // 模拟API延迟
      await mockDelay(300)

      const index = events.value.findIndex(e => e.id === id)
      if (index !== -1) {
        events.value[index] = { ...events.value[index], ...data, updated_at: new Date().toISOString() }

        // 保存到本地存储
        LocalStorageManager.saveEvents(events.value)
        console.log('事件更新已保存到本地存储')

        window.$message?.success('事件更新成功')
        return events.value[index]
      }
      return null
    } catch (error) {
      console.error('Update event error:', error)
      return null
    }
  }
  
  // 删除事件
  const deleteEvent = async (id: number) => {
    try {
      // 模拟API延迟
      await mockDelay(300)

      events.value = events.value.filter(e => e.id !== id)

      // 保存到本地存储
      LocalStorageManager.saveEvents(events.value)
      console.log('事件删除已保存到本地存储')

      window.$message?.success('事件删除成功')
      return true
    } catch (error) {
      console.error('Delete event error:', error)
      return false
    }
  }
  
  // 完成/取消完成事件
  const toggleEventCompletion = async (id: number, completed: boolean) => {
    try {
      await mockDelay(300)

      // 更新本地状态
      const index = events.value.findIndex(e => e.id === id)
      if (index !== -1) {
        const updatedEvent = {
          ...events.value[index],
          is_completed: completed,
          completed_at: completed ? new Date().toISOString() : undefined
        }
        events.value[index] = updatedEvent

        // 保存到本地存储
        LocalStorageManager.saveEvents(events.value)
        console.log('事件完成状态更新已保存到本地存储')

        window.$message?.success(completed ? '事件已完成' : '事件已取消完成')
        return updatedEvent
      }
      return null
    } catch (error) {
      console.error('Toggle event completion error:', error)
      return null
    }
  }
  
  // 获取指定日期的事件
  const getEventsByDate = (date: Date | string) => {
    const dateStr = formatDate(date, 'YYYY-MM-DD')
    return events.value.filter(event => {
      return event.start_date === dateStr || 
             (event.end_date && event.start_date <= dateStr && event.end_date >= dateStr)
    })
  }
  
  // 转换为日历事件格式
  const getCalendarEvents = computed((): CalendarEvent[] => {
    return events.value.map(event => {
      const eventType = eventTypes.value.find(t => t.id === event.event_type_id)
      
      return {
        id: String(event.id),
        title: event.title,
        start: new Date(event.start_date + (event.start_time ? ` ${event.start_time}` : '')),
        end: event.end_date ? new Date(event.end_date + (event.end_time ? ` ${event.end_time}` : '')) : undefined,
        color: eventType?.color || '#2196F3',
        isCompleted: event.is_completed,
        event
      }
    })
  })
  
  // 获取事件类型
  const getEventType = (id: number) => {
    return eventTypes.value.find(t => t.id === id)
  }
  
  // 获取饮食类型
  const getDietType = (id: number) => {
    return dietTypes.value.find(t => t.id === id)
  }
  
  // 初始化
  const init = async () => {
    await Promise.all([
      fetchEventTypes(),
      fetchDietTypes(),
      fetchEvents()
    ])
  }
  
  return {
    // state
    events: readonly(events),
    eventTypes: readonly(eventTypes),
    dietTypes: readonly(dietTypes),
    loading: readonly(loading),
    
    // getters
    getCalendarEvents,
    
    // actions
    fetchEvents,
    fetchEventTypes,
    fetchDietTypes,
    createEvent,
    updateEvent,
    deleteEvent,
    toggleEventCompletion,
    getEventsByDate,
    getEventType,
    getDietType,
    init
  }
})
